import { Avatar, Button, Checkbox, Divider, Icon, Image, Input, Message, Modal, Trigger } from "@arco-design/web-react"
import { useContext, useRef, useState } from "react";
import { UserInfo } from "../../../domain/user";
import { IconClose, IconDelete, IconMessage, IconPlus, IconSearch, IconUser, IconUserAdd, IconVideoCamera, IconVoice } from "@arco-design/web-react/icon";

import './styles_search.css';
import { useDispatch, useSelector } from "react-redux";
import { addConversation, changeIndex, fetchConversationList, refreshConversationByTargetId } from "../../../store/features/conversation";
import { ConversationType } from "../../../domain/im/entity";

import http from '../../../http';
import { LeoAvatar } from "../../../components/leo_Avatar";
import { openMessage } from "../../../store/features/message";
import { ChatContext } from "..";

const HighlightText: React.FC<any> = ({ text, highlightText }) => {
    if (!highlightText) {
        return <span>{text}</span>;
    }

    const highlightRegex = new RegExp(`(${highlightText})`, 'gi'); // 添加括号以创建捕获组
    const parts = text.split(highlightRegex);

    // 由于split会将匹配的文本也作为数组的一部分返回，我们需要在偶数索引上插入高亮的span
    const highlightedParts = parts.map((part: any, index: any) => {
        // 如果是奇数索引，说明这部分是被匹配的文本
        if (index % 2 !== 0) {
            return (
                <span key={index} className="highlighted-text">
                    {part}
                </span>
            );
        }
        return part; // 否则是普通文本，直接返回
    });

    return <span className="text-ellipsis line-clamp-1 break-words">{highlightedParts}</span>;
};



export const ChatSearch = () => {

    const users = useSelector((state: any) => state.friend.value.users)
    const conversationList = useSelector((state: any) => state.conversation.value.list)
    const [text, setText] = useState('');
    const searchInput: any = useRef<any>(null);
    const [visible, setVisible] = useState(false);

    const [contacts, setContacts] = useState<any>([]);

    const dispatch = useDispatch();


    const onchange = (e: any) => {
        const list = users.filter((item:any) => item.nickName.includes(e));
        setText(e);
        setContacts(list);
    }


    const { createGroup } = useContext(ChatContext);










    return <>
        <div className='flex flex-row items-center h-[60px] w-full pl-3'>
            <Trigger popup={() =>
                text.length > 0 ?
                    <div className='bg-white search_popup w-[265px] max-h-[700px] overflow-scroll ' >
                        {
                            contacts.length > 0 && <div >
                                <div className=" flex-col w-[265px] mt-2">
                                    <span className="text-gray-500 ml-4 ">联系人</span>
                                    <Divider className='mt-1 mb-0'></Divider>
                                </div>
                                {
                                    contacts.map((item:any, index:any) =>

                                        <div key={item.userId + 'index-1'} className="px-[5px]" onClick={() => {
                                            const index = conversationList.findIndex((con: any) => con.targetId == item.userId);
                                            if (index == -1) {
                                                dispatch(addConversation({
                                                    targetId: item.userId,
                                                    userName: item.userName,
                                                    userPortrait: item.userPortrait,
                                                    type: ConversationType.private,
                                                }))
                                            } else {
                                                dispatch(changeIndex(index))
                                            }
                                        }}>
                                            <div className="cursor-pointer p-2 contacts w-full flex flex-row justify-center items-center" onClick={() => setVisible(true)}>
                                                <LeoAvatar userPortrait={item.userPortrait} userName={item.nickName}></LeoAvatar>
                                                <span className="ml-2 text-[14px] w-[200px] text-ellipsis line-clamp-1 break-words">
                                                    {item.remark ? item.remark : item.nickName}
                                                </span>
                                            </div>
                                        </div>

                                    )
                                }
                            </div>
                        }


                        {/* {


                            <div >
                                <div className=" flex-col w-[265px] mt-2">
                                    <span className="text-gray-500 ml-4 ">聊天记录</span>
                                    <Divider className='mt-1 mb-0'></Divider>
                                </div>
                                <div className="px-[5px]">
                                    <div className="cursor-pointer p-2 contacts w-full flex flex-row justify-center items-center" onClick={() => setVisible(true)}>
                                        <div>  <Avatar size={40} shape="square">123</Avatar></div>
                                        <div className="text-left ml-[10px]">
                                            <span className="text-[14px] w-[200px] text-ellipsis line-clamp-1 break-words"> 孙连丽</span>
                                            <HighlightText text="Hello 1231212312313123, this is a test  ." highlightText="test" />
                                        </div>
                                    </div>


                                    <div className="cursor-pointer p-2 contacts w-full flex flex-row justify-center items-center" onClick={() => setVisible(true)}>
                                        <div>  <Avatar size={40} shape="square">123</Avatar></div>
                                        <div className="text-left ml-[10px]">
                                            <span className="text-[14px] w-[200px] text-ellipsis line-clamp-1 break-words"> 孙连丽</span>
                                            <HighlightText text="Hello 1231212312313123, this is a test  ." highlightText="test" />
                                        </div>
                                    </div>


                                    <div className="cursor-pointer p-2 contacts w-full flex flex-row justify-center items-center" onClick={() => setVisible(true)}>
                                        <div>  <Avatar size={40} shape="square">123</Avatar></div>
                                        <div className="text-left ml-[10px]">
                                            <span className="text-[14px] w-[200px] text-ellipsis line-clamp-1 break-words"> 孙连丽</span>
                                            <HighlightText text="Hello 1231212312313123, this is a test  ." highlightText="test" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        } */}


                    </div> : <div></div>

            } trigger='focus' position='bottom' className='mt-2'>
                <Input
                    ref={searchInput}
                    onChange={onchange}
                    maxLength={11}
                    prefix={<IconSearch />}
                    suffix={<IconPlus style={{ visibility: 'hidden' }}></IconPlus>}
                    placeholder='搜索'
                />
            </Trigger>

            <div onClick={() => createGroup(true)} className="h-[35px] w-[35px] ml-1 rounded-lg px-3 bg-gray-100 text-center flex flex-row items-center cursor-pointer">
                <IconPlus className="font-bold"></IconPlus>
            </div>
        </div>


    </>
}